package cn.edu.dhu.acm.oj.client.panel;

import cn.edu.dhu.acm.oj.common.paper.*;
import cn.edu.dhu.acm.oj.client.Control;
import cn.edu.dhu.acm.oj.common.config.Const;
import java.net.*;
import java.io.*;

public class PaperPanel extends javax.swing.JPanel {

	/** Creates new form PaperPanel */
	public PaperPanel() {
		initComponents();
		try {
			JEP_Problem.setContentType("text/html");
			((javax.swing.text.html.HTMLDocument) (JEP_Problem.getDocument())).setBase(new java.io.File(System.getProperty("java.io.tmpdir")).toURL());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setPaper() {
		try {
			JCB_Problem.removeAllItems();
			pb = Control.getPaperBean();
			papernum = pb.getProblemCount();
			for (int i = 0; i < papernum; i++) {
				JCB_Problem.addItem((char) ('A' + i) + ".   " + pb.getProblemAt(i).getTitle());
			}
			JCB_Problem.addItem("-Rule-");
			JEP_Problem.setText(pb.getProblemAt(0).transform());
			JEP_Problem.setCaretPosition(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void removePaper() {
		JCB_Problem.removeAllItems();
		JEP_Problem.setText("");
	}

	public void showOpenPaper() {
		JB_OpenPaper.setEnabled(true);
	}

	public void showDownload() {
		JB_Download.setEnabled(true);
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        JEP_Problem = new javax.swing.JEditorPane();
        ToolBar = new javax.swing.JToolBar();
        JCB_Problem = new javax.swing.JComboBox();
        JB_Download = new javax.swing.JButton();
        JB_OpenPaper = new javax.swing.JButton();

        setLayout(new java.awt.BorderLayout());

        JEP_Problem.setEditable(false);
        jScrollPane1.setViewportView(JEP_Problem);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);

        ToolBar.setFloatable(false);

        JCB_Problem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JCB_ProblemActionPerformed(evt);
            }
        });
        ToolBar.add(JCB_Problem);

        JB_Download.setText("Download");
        JB_Download.setEnabled(false);
        JB_Download.setFocusable(false);
        JB_Download.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        JB_Download.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        JB_Download.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_DownloadActionPerformed(evt);
            }
        });
        ToolBar.add(JB_Download);

        JB_OpenPaper.setText("OpenPaper");
        JB_OpenPaper.setFocusable(false);
        JB_OpenPaper.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        JB_OpenPaper.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        JB_OpenPaper.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_OpenPaperActionPerformed(evt);
            }
        });
        ToolBar.add(JB_OpenPaper);

        add(ToolBar, java.awt.BorderLayout.NORTH);
    }// </editor-fold>//GEN-END:initComponents

    private void JCB_ProblemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JCB_ProblemActionPerformed
		int i = JCB_Problem.getSelectedIndex();
		if (i < 0) {
			i = 0;
		}
		try {
			if (i == papernum) {
				Control.setNowProblemNum(0);
				JEP_Problem.setText(pb.getPaperDetail().getDecribe());
			} else {
				Control.setNowProblemNum(i);
				JEP_Problem.setText(pb.getProblemAt(i).transform());
			}
			JEP_Problem.setCaretPosition(0);
		} catch (Exception E) {
			E.printStackTrace();
		}
    }//GEN-LAST:event_JCB_ProblemActionPerformed

	private void JB_OpenPaperActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_OpenPaperActionPerformed
		if (downloaded || Control.getModel().startsWith("Local")) {
			javax.swing.JDialog dialog = new javax.swing.JDialog();
			PaperSelectPanel psp = new PaperSelectPanel(dialog);
			Control.getMainFrame().newDialog(dialog, psp, "Paper");
		} else {
			Control.getMainFrame().smallDialog("DownloadPaper First!\n", "ERROR", 0);
		}
}//GEN-LAST:event_JB_OpenPaperActionPerformed

	private void JB_DownloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_DownloadActionPerformed
		try {
			int bytesum = 0;
			int byteread = 0;

			int size = Control.getNetList().size();
			int ran = (int) (size * Math.random());
			java.net.URL url = new java.net.URL("http://" + Control.getNetList().get(ran) + Control.getPaperpath());
			//java.net.URL url = new java.net.URL(Control.getPaperpath());
			System.out.println("download : " + url.toString());
			URLConnection conn = url.openConnection();
			InputStream inStream = conn.getInputStream();

			String filename;
			if (Control.getPaperpath().endsWith(Const.ENCRYPTPAPERSUFFIX)) {
				filename = Control.getTmppath() + Const.CONTESTPREFIX +
						Control.getContestid() + Const.ENCRYPTPAPERSUFFIX;
			} else {
				filename = Control.getTmppath() + Const.CONTESTPREFIX +
						Control.getContestid() + Const.CLIENTPAPERSUFFIX;
			}
			FileOutputStream fs = new FileOutputStream(filename);

			byte[] buffer = new byte[1024];

			while ((byteread = inStream.read(buffer)) != -1) {
				bytesum += byteread;
				fs.write(buffer, 0, byteread);
			}
			Control.setContestPaperName(filename);
			downloaded = true;
			Control.getMainFrame().smallDialog("DownloadPaper OK!\n", "OK", 0);
		//setPaper(filename);
		} catch (Exception e) {
			downloaded = false;
			Control.getMainFrame().smallDialog("DownloadPaper Error!\n" + e.getMessage(), "Error", 0);
		}
	}//GEN-LAST:event_JB_DownloadActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton JB_Download;
    private javax.swing.JButton JB_OpenPaper;
    private javax.swing.JComboBox JCB_Problem;
    private javax.swing.JEditorPane JEP_Problem;
    private javax.swing.JToolBar ToolBar;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
	private PaperBean pb;
	private int papernum;
	private boolean downloaded = false;
}
